package com.zfei.gfb.device;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;
import java.util.Collection;
import java.util.Set;

/**
 * set缓存
 *
 * @author wangxb
 */
public class SetCache {

    private final StringRedisTemplate redis;

    public SetCache(RedisConnectionFactory factory) {
        this.redis = new StringRedisTemplate(factory);
    }

    public StringRedisTemplate getRedis() {
        return redis;
    }


    public void sAdd(String key, Collection<String> vals, Duration timeout) {
        this.redis.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection conn = (StringRedisConnection) connection;
            conn.sAdd(key, vals.toArray(new String[0]));
            conn.expire(key, timeout.getSeconds());
            return null;
        });
    }

    public Set<String> get(String key) {
        return this.redis.opsForSet().members(key);
    }


    public void delete(Collection<String> keys) {
        this.redis.delete(keys);
    }
}
